package com.rms.hkpc.signalr;

import android.content.Context;
import android.os.Handler;

import java.util.LinkedList;
import java.util.Queue;

public class SignalRClient {
    private final long sleep = 4000;
    private boolean isRunning = true;
    private SignalRChannel signalRChannel;
    private Handler receiveHandler;
    // 创建消息队列
    private Queue<SendMessage> sendMessageQueue = new LinkedList<>();
    private String url;
    private Thread t;
    private Context context;

    public SignalRClient(Context context, String url, Handler handler) {
        this.url = url;
        this.context = context;
        this.receiveHandler = handler;
        if (t == null) {
            t = new Thread(runnableSend);
            t.start();
        }
    }

    private Runnable runnableSend = new Runnable() {
        @Override
        public void run() {
            while (isRunning) {
                // 刷新连接状态
                if (signalRChannel == null || !signalRChannel.isConnected()) {
                    try {
                        reConnect();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                while (!sendMessageQueue.isEmpty()) {
                    SendMessage sendMessage = sendMessageQueue.poll();
                    signalRChannel.send(sendMessage.getMethod(), sendMessage.getMessage());
                }
                try {
                    Thread.sleep(sleep);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    /**
     * 发送消息
     *
     * @param method
     * @param messages
     */
    public void send(String method, Object... messages) {
        SendMessage sendMessage = new SendMessage(method, messages);
        sendMessageQueue.offer(sendMessage);
    }

    /**
     * 重连
     */
    private void reConnect() {
        if (signalRChannel != null) {
            signalRChannel.stopConnect();
            signalRChannel = null;
        }
        signalRChannel = new SignalRChannel(url, receiveHandler);
        signalRChannel.startConnect();
    }

    /**
     * 登出
     */
    public void logOut() {
        if (signalRChannel != null) {
            isRunning = false;
            signalRChannel.stopConnect();
            signalRChannel = null;
        }
        if (t != null) {
            t.interrupt();
            t = null;
        }
    }
}
